﻿using Core.AdminUI.V2.Controllers.Base;
using Core.AdminUI.V2.Models.BaseTree;
using Core.FrameWork.Commons.ApiResult;
using Core.FrameWork.Commons.Loging;
using Core.FrameWork.Models;
using Core.FrameWork.Models.Models.System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Core.AdminUI.V2.Controllers
{
    public class BaseTreeController : BaseController
    {
        public BaseTreeController(AdminContext db) : base(db)
        {
        }

        // GET: BaseTree
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Main()
        {
            return View();
        }
        /// <summary>
        /// 获取数据树子节点
        /// </summary>
        /// <param name="id"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("获取数据树子节点", LogResponseData = false)]
        public string QueryTreeByPid(Guid id = default(Guid), int flag = 0)
        {
            JArray listArray = new JArray();


            var list = _adminContext.SysBaseTree.Where(m => m.PId == id && m.IsDelete == 0).OrderBy(m => m.Sort).ThenBy(m => m.CreateTime).ToList();

            if (flag == 1 && id == Guid.Empty)
            {
                JObject obj = new JObject
                {
                    ["id"] = Guid.Empty,
                    ["pId"] = Guid.Empty,
                    ["name"] = "根节点",
                    ["isParent"] = false,
                    ["open"] = true
                };
                listArray.Add(obj);
            }
            foreach (var item in list)
            {

                JObject obj = new JObject
                {
                    ["id"] = item.Id,
                    ["pId"] = item.PId,
                    ["name"] = item.TreeName,
                    ["isParent"] = _adminContext.SysBaseTree.Count(s => s.PId.Equals(item.Id)) > 0,
                    ["open"] = true
                };

                listArray.Add(obj);
            }



            return listArray.ToString();
        }
        /// <summary>
        /// 获取数据树列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pId"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("获取数据树列表", LogResponseData = false)]
        public PageResult<SysBaseTree> GetList(int pageIndex = 1, int pageSize = 10, Guid pId = default(Guid))
        {

            Expression<Func<SysBaseTree, bool>> where = m => m.PId == pId && m.IsDelete == 0;
            int cnt = _adminContext.SysBaseTree.Count(where);
            var listBaseTrees = _adminContext.SysBaseTree.Where(where)
            .OrderByDescending(m => m.Sort).OrderBy(m => m.CreateTime)
            .Skip((pageIndex - 1) * pageSize)
            .Take(pageSize)
            .ToList();
            return ApiRespHelp.getApiDataListByPage<SysBaseTree>(listBaseTrees, cnt, pageIndex, pageSize);

        }
        /// <summary>
        /// 获取数据树详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("获取数据树详情", LogResponseData = false)]
        public CommonResult<SysBaseTree> GetTreeInfo(Guid Id = default(Guid))
        {
            var baseTree = _adminContext.SysBaseTree.Find(Id);
            if (baseTree == null)
                return ApiRespHelp.getError<SysBaseTree>(-100, "未获取到信息");

            if (baseTree.PId != Guid.Parse("00000000-0000-0000-0000-000000000000"))
            {
                baseTree.PName = _adminContext.SysBaseTree.Find(baseTree.PId)?.TreeName;
            }
            else
            {
                baseTree.PName = "根节点";
            }


            return ApiRespHelp.GetApiData(baseTree);

        }
        /// <summary>
        /// 修改数据树信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("修改数据树信息", LogResponseData = false)]
        public CommonResult Edit(SysBaseTree model)
        {

            if (model.Id == model.PId && model.PId != Guid.Empty)
                return ApiRespHelp.getError(-100, "不能选择自身作为父节点");
            var old = _adminContext.SysBaseTree.Find(model.PId);
            string ppath = old == null ? "," : old.Path;
            if (model.Id == Guid.Empty)
            {
                _adminContext.SysBaseTree.Add(model);
            }
            else
            {
                //context.Database.
                var oldmodel = _adminContext.SysBaseTree.AsNoTracking().FirstOrDefault(m => m.Id == model.Id);
                //var oldmodel = context.BaseTree.Find(model.Id);
                model.CreateTime = oldmodel.CreateTime;
                var entry = _adminContext.Entry(model);
                _adminContext.Set<SysBaseTree>().Attach(model);
                entry.State = EntityState.Modified;
                if (oldmodel.PId != model.PId)//如果父节点更换，应更新所有子树的path
                {
                    ////UPDATE dbo.BaseTree SET Path=REPLACE(Path,',10000,10001,',',10007,10001,') WHERE CHARINDEX(',10000,10001,',[Path],0)>0
                    //string sql = $@"UPDATE BaseTree
                    //SET Path = '{ppath}'+ SUBSTRING(Path, CHARINDEX(',{model.Id},', Path, 0) + 1, LEN(Path) - CHARINDEX(',{model.Id},', Path, 0))
                    //WHERE CHARINDEX(',{model.Id},', [Path], 0) > 0;";
                    //_adminContext.Database.ExecuteSqlRaw(sql);
                }
            }
            int num = _adminContext.SaveChanges();
            if (num > 0)
            {
                //修改路径
                model.Path = $"{ppath}{model.Id},";
                _adminContext.SaveChanges();


                return ApiRespHelp.getSuccess("提交成功");
            }
            return ApiRespHelp.getError(-100, "提交失败");

        }
        /// <summary>
        /// 删除数据树数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("删除数据树数据", LogResponseData = false)]
        public CommonResult Delete(Guid Id = default(Guid))
        {
            if (Id == Guid.Empty)
                return ApiRespHelp.getError(-100, "请选中要删除的树菜单");
            var baseTree = _adminContext.SysBaseTree.Find(Id);
            if (baseTree == null)
                return ApiRespHelp.getError(-100, "未获取到信息");
            baseTree.IsDelete = 1;
            int num = _adminContext.SaveChanges();
            if (num > 0)
                return ApiRespHelp.getSuccess("删除成功");
            return ApiRespHelp.getError(-100, "删除失败");
        }

        /// <summary>
        /// 根据父ID获取select 下拉框的值
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("根据父ID获取select 下拉框的值", LogResponseData = false)]
        public List<SelectData> GetListByPid(Guid pid)
        {


            var list = _adminContext.SysBaseTree.Where(m => m.State && m.PId == pid)
                .Select(m => new SelectData { name = m.TreeName, value = m.Id.ToString() }).ToList();
            return list;


        }
    }
}